package cn.wsalix.order.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.anlaser.service.impl.BasicServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.biz.form.FreemarkerForm;
import cn.wsalix.config.AppConfig;
import cn.wsalix.freemarker.FreemarkerUtil;
import cn.wsalix.observable.service.PayService;
import cn.wsalix.order.entity.MasterTuan;
import cn.wsalix.order.entity.Order;
import cn.wsalix.order.form.WeiXinNotifyForm;
import cn.wsalix.order.repository.TuanRepository;
import cn.wsalix.order.service.TuanService;
import cn.wsalix.shop.entity.Product;
import cn.wsalix.shop.form.TuanForm;
import cn.wsalix.shop.service.ProductService;

@Service("masterTuanService")
public class TuanServiceImpl extends
		BasicServiceImpl<TuanForm, TuanRepository, MasterTuan>
		implements TuanService {
	@Autowired
	private TuanRepository tuanRepository;
	@Autowired
	private ProductService productService;
	@Override
	public String module() {
		return "/user/tuan";
	}

	@Override
	public TuanRepository getRepository() {
		return tuanRepository;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(TuanForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getId() != null && form.getId() != 0) {
			filters.put("id", new SearchFilter("id", Operator.EQ, form.getId()));
		}
		if (form.getOrderId() != null && form.getOrderId() != 0) {
			filters.put("orderId", new SearchFilter("orderId", Operator.EQ,
					form.getOrderId()));
		}
		if (form.getProductId() != null && form.getOrderId() != 0) {
			filters.put("productId", new SearchFilter("productId", Operator.EQ,
					form.getProductId()));
		}

		return filters;
	}

	@Override
	public Class<MasterTuan> getEntityClazz() {
		return MasterTuan.class;
	}

	@Override
	public MasterTuan findByOrderId(Long orderId) {
		return tuanRepository.findOne(orderId);
	}

	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof PayService) {
			PayService payService = (PayService) o;

			if (arg instanceof WeiXinNotifyForm) {
				WeiXinNotifyForm form = (WeiXinNotifyForm) arg;
				Order order = payService.getOrder();
				if (payService.isTreate()) {
					if (order.isTuan()) {// 团购
						if (order.isMaster()) { // 主团购
							MasterTuan masterTuan = findByOrderId(order.getId());
							GregorianCalendar gc = new GregorianCalendar();
							Date currDate = new Date();
							gc.setTime(currDate);
							masterTuan.setBeginTime(gc.getTime());
							// masterTuan.setBeginTime(format.format(currDate));
							gc.add(5, 3);
							masterTuan.setEndTime(gc.getTime());
							// masterTuan.setEndTime(format.format(gc.getTime()));
							edit(masterTuan);							
						}else{
							
						}
						// 计算是否满团
						// 生成我的团信息
						// freemarkerUtil.GenerateFile(form);
						buildHtml(order);
					}
				}

			}
		}
	}
	@Autowired
	private FreemarkerUtil freemarkerUtil;
	@Autowired
	private AppConfig appConfig;

	public String buildHtml(Order order) {
		FreemarkerForm form = new FreemarkerForm();
		form.setTemplateDir(appConfig.getFtlPath());
		try {
			File outFile=new File(appConfig.getHtmlOutPath(),
					"order_"+order.getId()+".html");
			
			if(!outFile.exists()){
				outFile.createNewFile();
			}
			Writer out = new OutputStreamWriter(
					new FileOutputStream(outFile), "GBK");
			Map<String,Object> resMap=new HashMap<String,Object>();
			resMap.put("order", order);
			form.setParaMap(resMap);
			form.setTemplateFile("tuan_info.ftl");
			form.setOut(out);
			freemarkerUtil.buildFile(form);
			return "order_"+order.getId()+".html";
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public String buildHtml(MasterTuan tuan) {
		FreemarkerForm form = new FreemarkerForm();
		form.setTemplateDir(appConfig.getFtlPath());
		try {
			File outFile=new File(appConfig.getHtmlOutPath(),
					"order_"+tuan.getId()+".html");
			
			if(!outFile.exists()){
				outFile.createNewFile();
			}
			Writer out = new OutputStreamWriter(
					new FileOutputStream(outFile), "UTF-8");
			Map<String,Object> resMap=new HashMap<String,Object>();
			Product product= productService.findById(tuan.getProductId());
			resMap.put("templetDir", appConfig.getBackTheme());
			resMap.put("product", product);
			resMap.put("tuan", tuan);
			resMap.put("masterOrder", tuan.getMasterOrder());
			form.setParaMap(resMap);
			form.setTemplateFile("tuan_info.ftl");
			form.setOut(out);
			freemarkerUtil.buildFile(form);
			return "order_"+tuan.getId()+".html";
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String buildHtml(Long fkId) {
		MasterTuan tuan=tuanRepository.findOne(fkId);
		return buildHtml(tuan);
	}
}
